package logic

import (
	"context"
	"fmt"

	"wxapi/internal/services"
	"wxapi/internal/svc"
	"wxapi/internal/types"

	"gitee.com/dromara/carbon/v2"
	"github.com/shopspring/decimal"
	"github.com/zeromicro/go-zero/core/logx"
)

type AddCarLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddCarLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCarLogic {
	return &AddCarLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddCarLogic) AddCar(req *types.AddCarReq) (resp *types.AddCarResp, err error) {
	userId, err := services.GetUserIdBySession(l.ctx, l.svcCtx, req.Session)
	if err != nil {
		return nil, err
	}

	beginTime := carbon.ParseByFormat(fmt.Sprintf("%s %s", req.Date, req.Time), "Y-m-d H:i")
	err = services.AddCarGoods(l.ctx, l.svcCtx, userId, req.DoctorID, req.ItemID, beginTime)
	if err != nil {
		return nil, err
	}

	cars, err := services.GetCarGoods(l.ctx, l.svcCtx, userId)
	if err != nil {
		return nil, err
	}
	totalAmount := decimal.NewFromFloat(0.0)
	for _, car := range cars {
		totalAmount = totalAmount.Add(car.Price)
	}

	resp = &types.AddCarResp{
		Amount: totalAmount.InexactFloat64(),
		Count:  int64(len(cars)),
	}

	return
}
